package com.nexus.plugin.security.exception;

import com.nexus.core.utils.ResponseUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录失败处理
 *
 * @Date 2025/7/31 17:30
 * @Author luzhengning
 **/

@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        // 设置响应内容类型
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 根据不同异常类型返回不同消息
        String message = "登录失败";
        if (exception.getMessage().contains("Bad credentials")) {
            message = "用户名或密码错误";
        } else if (exception.getMessage().contains("User is disabled")) {
            message = "账号已被禁用";
        } else if (exception.getMessage().contains("User is locked")) {
            message = "账号已被锁定";
        }

        // 创建错误响应
        ResponseUtils.sendResponse(response, 401, null, message);
    }
}
